#include "unp.h"
#include "var.h"
#include "var1.h"

int getServerResponse(int sockfd) {

	int n;
	int wordN;
	Word word[WORD_NUM];
	char buf[MAXLINE];
	char reqM[MAXLINE];
	char port1[WORD_LENG];
	int i_port1;
	char port2[WORD_LENG];
	int i_port2;
	char *p;

	for (;;) {
		memset(&buf, 0x00, sizeof(buf));
		n = Read(sockfd, buf, MAXLINE);
		//debugPrint(buf,MSG_IS_RES);
		fprintf(stderr, "%s", buf);
		if (strstr(buf, "227") != NULL) {
			p = strtok(buf, "(");
			p = strtok(NULL, ","); //192
			p = strtok(NULL, ","); //168
			p = strtok(NULL, ","); //56
			p = strtok(NULL, ","); //2
			p = strtok(NULL, ","); //193
			strcpy(port1, p);
			fprintf(stderr, "first port Num is %s\n", port1);
			i_port1 = atoi(port1);
			p = strtok(NULL, ")"); //last portnum
			strcpy(port2, p);
			i_port2 = atoi(port2);
			fprintf(stderr, "second port Num is %s\n", port2);
			I_DATA_PORT_NUM = (i_port1 * 256) + i_port2;
			snprintf(DATA_PORT_NUM, MAXLINE, "%d", I_DATA_PORT_NUM);
		}
		if (buf[0] == '5') {
			return 5;
		} else if (buf[0] == '4') {
			return 4;
		} else if (buf[0] == '3') {
			return 3;
		} else if (buf[0] == '2') {
			return 2;
		} else if (buf[0] == '1') {
			return 1;
		}
	}
}

void getServerFTPData(int filesockfd, int requestN) {

	int n;
	char buf[MAXLINE];
	int filefd;


	switch (requestN) {
	case LS:
		n = Read(filesockfd, buf, MAXLINE);
		fprintf(stderr, "%s", buf);
		break;
	case TYPE:
		n = Read(filesockfd, buf, MAXLINE);
		fprintf(stderr, "%s", buf);
		break;
	case GET:
		//n = Read(filesockfd, buf, MAXLINE);
		getFile(filesockfd, PATHNAME);
		break;
	case PUT:
		putFile(filesockfd, PATHNAME);
		break;
	}

}

void getFile(int data_sock, char *filename) {

	int file_discriptor;
	int file_length;
	int n;
	char buf[MAXLINE];

	fprintf(stderr, "get file name is %s\n", filename);
	if (read(data_sock, buf, sizeof(buf)) == -1) {
		fprintf(stderr, "SOCKET IS NOT READABLE\n");
	}
	file_discriptor = open(PATHNAME, O_CREAT | O_WRONLY | O_TRUNC);
	write(file_discriptor, buf, sizeof(buf));

	close(file_discriptor);
}

void putFile(int data_sock, char *filename) {
	int file_discriptor;
	int file_length;
	int n;
	char send_message[MAXLINE];

	file_discriptor = open(filename, O_RDONLY, S_IRUSR | S_IWUSR);

	if (file_discriptor > 0) {

		while((file_length = read(file_discriptor, send_message,MAXLINE)) != 0) {
			write(data_sock,send_message,file_length);
			memset(send_message,0,strlen(send_message));
		}
	}

	else if (file_discriptor < 0) {
		fprintf(stderr,"File Not Found!!\n");
	}


}

